/*
 * @Copyright (c) 2018 缪聪(mcg-helper@qq.com)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");  
 * you may not use this file except in compliance with the License.  
 * You may obtain a copy of the License at  
 *     
 *     http://www.apache.org/licenses/LICENSE-2.0  
 *     
 * Unless required by applicable law or agreed to in writing, software  
 * distributed under the License is distributed on an "AS IS" BASIS,  
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
 * See the License for the specific language governing permissions and  
 * limitations under the License.
 */

package com.mcgrobot.controller.fs;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.mcgrobot.common.Constants;
import com.mcgrobot.controller.base.BaseController;
import com.mcgrobot.domain.FileInfo;
import com.mcgrobot.entity.common.McgResult;
import com.mcgrobot.service.FsService;
import com.mcgrobot.util.FsZipCompressor;
import com.mcgrobot.util.Tools;

@Controller
@RequestMapping(value="/fs")
public class FsController extends BaseController {

	private static Logger logger = LoggerFactory.getLogger(FsController.class);
	@Autowired
	private FsService fsService;
	
	@RequestMapping(value="/index")
	public ModelAndView index(String path) throws Exception{
		ModelAndView mv = this.getModelAndView();
		mv.setViewName("fs/index");
		
		List<FileInfo> fileInfoList = fsService.getCurDirDetails(Constants.FS_PATH);
		mv.addObject("fsPath", Constants.FS_PATH);
		mv.addObject("fileInfoList", fileInfoList);
		mv.addObject("version", Constants.VERSION);
		return mv;
	}
	
    @RequestMapping(value="enterSubDir", method=RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public McgResult enterSubDir(String subPath) throws ClassNotFoundException, IOException {
    	
    	McgResult mcgResult = new McgResult();
    	if(StringUtils.isEmpty(subPath)) {
    		mcgResult.setStatusCode(0);
    		mcgResult.setStatusMes("子目录路径为空！");
    		logger.error("子目录路径为空！");
    		return mcgResult;
    	}
    	List<FileInfo> fileInfoList = fsService.getCurDirDetails(subPath);
    	mcgResult.getResultMap().put("fileInfoList", fileInfoList);
    	return mcgResult;
    }
    
    @RequestMapping(value="createFolder", method=RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public McgResult createFolder(String folderPath, String folderName) throws ClassNotFoundException, IOException {
    	
    	McgResult mcgResult = new McgResult();
    	if(StringUtils.isEmpty(folderPath) || StringUtils.isEmpty(folderName)) {
    		mcgResult.setStatusCode(0);
    		mcgResult.setStatusMes("创建路径为空或文件夹名称为空！");
    		logger.error("创建路径为空或文件夹名称为空！");
    		return mcgResult;
    	}
    	
		File targetFile = new File(folderPath + "/" + folderName);
    	if (!targetFile.exists()) {
    		targetFile.mkdirs();
    	}
    	
    	FileInfo fileInfo = new FileInfo();
    	fileInfo.setFileType("dir");
    	fileInfo.setFileName(folderName);
    	fileInfo.setFilePath(folderPath);
    	mcgResult.getResultMap().put("fileInfo", fileInfo);
    	return mcgResult;
    }
    
    @RequestMapping(value="fileDelete", method=RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public McgResult fileDelete(String filePath) throws ClassNotFoundException, IOException {
    	
    	McgResult mcgResult = new McgResult();
    	if(StringUtils.isEmpty(filePath)) {
    		mcgResult.setStatusCode(0);
    		mcgResult.setStatusMes("删除文件路径为空！");
    		logger.error("删除文件路径为空！");
    		return mcgResult;
    	}
    	
    	try {
    		File targetFile = new File(filePath);
			if(targetFile.isFile()) {
				mcgResult.setStatusCode(targetFile.delete() ? 1:0);
			} else {
				logger.error("文件管理模块，删除文件错误：删除目标非文件，{}", filePath);
				mcgResult.setStatusCode(0);
			}
    	} catch (Exception e) {
    		logger.error("文件管理模块，删除文件错误：删除目标非文件，{}，失败信息：", filePath, e);
    		mcgResult.setStatusCode(0);
		}
    	
    	return mcgResult;
    }
    
    @RequestMapping(value="folderDelete", method=RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public McgResult folderDelete(String filePath) throws ClassNotFoundException, IOException {
    	
    	McgResult mcgResult = new McgResult();
    	if(StringUtils.isEmpty(filePath)) {
    		mcgResult.setStatusCode(0);
    		mcgResult.setStatusMes("删除文件夹路径为空！");
    		logger.error("删除文件夹路径为空！");
    		return mcgResult;
    	}
    	
    	try {
			File folderFile = new File(filePath);
			if(folderFile.isDirectory()) {
				FileUtils.deleteDirectory(folderFile);
			} else {
				logger.error("文件管理模块，删除文件夹错误：删除目标非文件夹，{}", filePath);
				mcgResult.setStatusCode(0);
			}
			mcgResult.setStatusCode(1);
    	} catch (Exception e) {
    		logger.error("文件管理模块，删除文件夹失败，路径{}，失败信息：", filePath, e);
    		mcgResult.setStatusCode(0);
		}
		
    	
    	return mcgResult;
    }
    
    @RequestMapping(value="fsRename", method=RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public McgResult fsRename(String filePath, String oldFileName, String newFileName) throws ClassNotFoundException, IOException {
    	
    	McgResult mcgResult = new McgResult();
    	if(StringUtils.isEmpty(filePath)) {
    		mcgResult.setStatusCode(0);
    		mcgResult.setStatusMes("重命名文件路径为空！");
    		logger.error("重命名文件路径为空！");
    		return mcgResult;
    	}
    	
    	try {
	    	File oldFile = new File(filePath + "/" + oldFileName);
			File newFile = new File(filePath + "/" + newFileName);
			mcgResult.setStatusCode(oldFile.renameTo(newFile) ? 1:0);
    	}catch (Exception e) {
    		mcgResult.setStatusCode(0);
    		mcgResult.setStatusMes("文件重命名出错，请重试！");
			logger.error("文件重命名出错：", e);
		}
    	
    	return mcgResult;
    }
    
    @RequestMapping(value="upload", method=RequestMethod.POST)
    @ResponseBody
    public McgResult upload(@RequestParam(value = "file_data", required = true)MultipartFile file, @RequestParam(value = "filePath", required = true)String filePath,  HttpSession session) {
    	
    	McgResult result = new McgResult();
    	try {
	    	if(file == null) {
	    		result.setStatusCode(0);
	    		result.setStatusMes("上传文件为空！");
	    		logger.error("上传文件为空！");
	    	} else {
	    		File targetFile = new File(filePath + "/" + file.getOriginalFilename());
	        	if (!targetFile.getParentFile().exists()) {
	        		targetFile.getParentFile().mkdirs();
	        	}  
	        	file.transferTo(targetFile);
	        	
		    	FileInfo fileInfo = new FileInfo();
		    	fileInfo.setFileName(file.getOriginalFilename());
		    	fileInfo.setFilePath(filePath);
		    	fileInfo.setFileType("file");
		    	result.getResultMap().put("fileInfo", fileInfo);
	    	}
    	} catch (Exception e) {
    		result.setStatusCode(0);
    		result.setStatusMes("上传文件出错，请重试！");
    		logger.error("上传文件出错，请重试！", e);
		}
    	return result;
    }
    
	@RequestMapping(value="/initFsFileUpolad")
	public ModelAndView initFsFileUpolad() throws Exception{
		ModelAndView mv = this.getModelAndView();
		mv.setViewName("fs/uploadFileModal");
		return mv;
	}
	
	@RequestMapping("download")
	public ModelAndView download(String filePath, HttpServletRequest request, HttpServletResponse response) {
	    
        ModelAndView modeAndView = new ModelAndView("redirect:/download");
    	
        if(!StringUtils.isEmpty(filePath)) {
        	filePath = filePath.replaceAll("\\\\", "/");
            modeAndView.addObject("filePath", filePath);
            int pos = filePath.lastIndexOf("/");
        	String fileName = filePath.substring(pos+1);
            modeAndView.addObject("fileName", fileName);
            
        }

    	return modeAndView;
	}
	
	@RequestMapping("dirDownload")
	public String dirDownload(String filePath, HttpServletRequest request, HttpServletResponse response) {
		if(StringUtils.isEmpty(filePath)) {
			logger.error("文件资源模块下载目录路径为空！");
			return null;
		}
		String downFileName = filePath.substring(filePath.lastIndexOf("/") + 1) + ".zip";
        response.setCharacterEncoding(Constants.CHARSET.toString());
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + Tools.convertCharacterEncoding(request, downFileName));
        OutputStream os = null;
        
        try {
            os = response.getOutputStream();
            FsZipCompressor fzc = new FsZipCompressor(os);
            List<String> filePathList = new ArrayList<>();
            filePathList.add(filePath);
            fzc.compress(filePathList);

        }catch (Exception e) {
        	logger.error("文件资源模块下载文件出错，异常信息：", e);
        }finally {
            try {
                if(os != null) {
                    os.close();
                }
            } catch (IOException e) {
            	logger.error("导入流程文件后关闭流出错，异常信息：", e);
            }
        }
        
        return null;
	}
	
}
